<template>
  <view class="page">
    <view class=" container">
      <view class="header">
        <text class="title">正風學習中心AI测评</text>
      </view>
      <view class="circle-wrapper">
        <canvas
          class="circle"
          canvas-id="countdownCircle"
          :style="{ width: size + 'px', height: size + 'px' }"
        />
        <view class="countdown-number">
          {{ count }}
        </view>
      </view>
      <view class="desc-title">
        准备测试
      </view>
      <view class="desc-tip">
        请把手机音量调整至理想音量
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { ref, onMounted, onUnmounted, defineComponent } from 'vue';
import tempdata from '../../temp-data.js';
import question from '@/api/question';

export default defineComponent({
  data() {
    return {
      curLib: 'mh_secur_4',
      libs: ['mh_secur_4', 'mh_secur_5'],
      total: 3,
      count: 3,
      size: 160,
      timer: null as any,
      audio: null as any
    };
  },
  mounted() {
    this.drawCircle(1);
    this.startCountdown();
  },
  unmounted() {
    if (this.timer) clearInterval(this.timer);
    if (this.audio) this.audio.destroy();
  },
  methods: {
    playTick() {
      if (!this.audio) {
        this.audio = uni.createInnerAudioContext();
        this.audio.src = '/static/audio/tick.mp3';
      }
      this.audio.stop();
      this.audio.play();
    },
    drawCircle(percent: number) {
      const ctx = uni.createCanvasContext('countdownCircle');
      const radius = this.size / 2 - 10;
      ctx.clearRect(0, 0, this.size, this.size);
      // 背景环
      ctx.beginPath();
      ctx.arc(
        this.size / 2,
        this.size / 2,
        radius,
        0,
        2 * Math.PI,
        false
      );
      ctx.setStrokeStyle('#e6eaf2');
      ctx.setLineWidth(10);
      ctx.stroke();
      // 进度环
      ctx.beginPath();
      ctx.arc(
        this.size / 2,
        this.size / 2,
        radius,
        -Math.PI / 2,
        -Math.PI / 2 + 2 * Math.PI * percent,
        false
      );
      // @ts-ignore
      const gradient = ctx.createLinearGradient(this.size / 2, this.size / 2 - radius, this.size / 2, this.size / 2 + radius);
      // @ts-ignore
      gradient.addColorStop(0, '#338bff');
      // @ts-ignore
      gradient.addColorStop(1, '#00eaff');
      // @ts-ignore
      ctx.setStrokeStyle(gradient as any);
      ctx.setLineWidth(10);
      ctx.stroke();
      ctx.draw();
    },
    startCountdown() {
      this.count = this.total;
      this.drawCircle(1);
      this.playTick();
      this.timer = setInterval(() => {
        this.count--;
        this.playTick();
        this.drawCircle(this.count / this.total);
        if (this.count <= 0) {
          clearInterval(this.timer);
          setTimeout(() => {
            // uni.redirectTo({ url: '/pages/exam/exam' });
			this.onMode('exam')
          }, 300);
        }
      }, 1000);
    },
    onMode(type: string) {
      uni.navigateTo({
        // url: '/uni_modules/sv-exam-plus/pages/exam/exam',
        url: '/pages/exam/exam',
        success: async (res: any) => {
          res.eventChannel.emit('e-transmit-exams', {
            param: {
              from_lib: this.curLib,
              unit: 'unit-1'
            },
            opt: {
              lib_name: this.curLib,
              type: type
            },
            apifunc: {
              examList: this.getExamList
            }
          });
        }
      });
    },
    changeLib() {
      uni.showActionSheet({
        itemList: this.libs,
        success: (res: any) => {
          this.curLib = this.libs[res.tapIndex];
        }
      });
    },
    toSimple() {
      uni.navigateTo({
        url: '/pages/simple/simple',
        success: async (res: any) => {
          const examDataRes = await this.getExamList({ from_lib: this.curLib, unit: 'unit-1' });
          res.eventChannel.emit('e-transmit-exams', {
            data: examDataRes.data
          });
        }
      });
    },
    /**
     * ajax请求 此处仅简化代码 不做封装 封装方式请移步以下链接
     * @tutorial https://ext.dcloud.net.cn/plugin?id=16529
     */
    async getExamListold(params: any = {}) {
      let data: any = await question.getQuestionList({});
      console.log('data', data); // 现在这里才是实际数据
      console.log('data.list', data && (data as any).list);
      (tempdata as any).data = (data as any).list;
      return tempdata;
    },
    async getExamList(params: any = {}) {
      return tempdata;
      // let data: any = await question.getQuestionList(params);
      // console.log('data', data);
      // const from_lib = params.from_lib || '';
      // const unit = params.unit || '';
      // const examList = ((data as any).list || []).map((q: any, idx: number) => this.convertQuestionToExamItem(q, { from_lib, unit, index: idx + 1 }));
      // return { data: examList };
    },
    convertQuestionToExamItem(q: any, { from_lib = '', unit = '', index = 1 } = {}) {
      return {
        _id: q.id ? String(q.id) : '', // 或者用 uuid
        from_lib,
        unit,
        exam_id: `${from_lib}-${unit}-${index}`,
        exam_name: q.question ? `<p>${q.question}</p>` : '',
        exam_title: q.question || '',
        exam_index: index,
        exam_type: q.type || 0,
        exam_option: Object.keys(q.option || {}).map(key => ({
          key,
          value: `<div>${q.option[key]}</div>`
        })),
        options_type: q.options_type,
        exam_answer: q.true ? String(q.true).split(',').map((s: string) => s.trim()).filter(Boolean) : [],
        analysis: q.analysis ? `<p>${q.analysis}</p>` : '',
        comment: q.comment ? `<p>${q.comment}</p>` : ''
      };
    }
  }
});
</script>

<style scoped>
.page {
  background: linear-gradient(135deg, #e6f0ff 0%, #b3d1ff 100%);
}
.container {
  min-height: 100vh;
  background: url('/static/image/top_bg.png') top center no-repeat;
  background-size: 100% 400rpx, 100% 100%;
  /* background: linear-gradient(135deg, #e6f0ff 0%, #b3d1ff 100%); */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.header {
  margin-top: 40rpx;
  margin-bottom: 60rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
}
.circle-wrapper {
  position: relative;
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.circle {
  width: 160px;
  height: 160px;
}
.countdown-number {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 60rpx;
  font-weight: bold;
  color: #338bff;
  z-index: 2;
}
.desc-title {
  margin-top: 60rpx;
  font-size: 40rpx;
  font-weight: bold;
  color: #222;
  text-align: center;
}
.desc-tip {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #888;
  text-align: center;
}
</style>